<!DOCTYPE html>
<html>
<head>
<script src="../../resources/js-test.js"></script>
<script src="resources/common.js"></script>
</head>
<body>
<p id="description"></p>
<div id="console"></div>

<script>
description("Tests crypto.subtle.importKey() using a BufferSource that is modified during algorithm normalization");

jsTestIsAsync = true;

var kKeyDataHex = "30112233445566778899aabbccddeeff";

keyData = hexStringToUint8Array(kKeyDataHex);

function corruptKeyData()
{
    debug("Corrupting keyData...");
    keyData[0] = 0;
    keyData[1] = 0;
}

// This algorithm has a custom getter that modifies the key data.
var importAlgorithm = {
    get name() {
        debug("Accessed name property");
        corruptKeyData();
        return 'aes-cbc';
    }
};

var extractable = true;
var usages = ['encrypt', 'decrypt'];

debug("Importing key...");
crypto.subtle.importKey('raw', keyData, importAlgorithm, extractable, usages).then(function(result) {
    debug("Exporting key...");
    return crypto.subtle.exportKey('raw', result);
}).then(function(result) {
    bytesShouldMatchHexString("Exported data", kKeyDataHex, result);

    debug("Importing key (again)...");
    return crypto.subtle.importKey('raw', keyData, "AES-CBC", extractable, usages);
}).then(function(result) {
    debug("Importing second key...");
    return crypto.subtle.exportKey('raw', result);
}).then(function(result) {
    // This time the imported key should reflect the modified version.
    bytesShouldMatchHexString("Exported data", "00002233445566778899aabbccddeeff", result);
}).then(finishJSTest, failAndFinishJSTest);

</script>

</body>
</html>
